from _md5 import md5
from dataclasses import dataclass
from datetime import datetime
from hashlib import sha256
from typing import List,Any
import models
from exts import db
from models import article
from models.article import Article
from models.role import Role

@dataclass
class User(db.Model):
    __tablename__ = "user"
    id:int = db.Column(db.Integer,primary_key=True,autoincrement=True)
    username:str = db.Column(db.String(255),nullable=False)
    realname:str = db.Column(db.String(255), comment='真实名字')
    password:str = db.Column(db.String(255),nullable=False)
    email:str = db.Column(db.String(255),nullable=False)
    avatar:str = db.Column(db.String(255), comment='头像', default="/static/admin/admin/images/avatar.jpg")
    remark:str = db.Column(db.String(255), comment='备注')
    status:int = db.Column(db.Integer, default=1, comment='状态')
    dept_id = db.Column(db.Integer, comment='部门id')
    phone:str = db.Column(db.String(25), comment='手机号')
    role = db.relationship('Role', secondary="user_role", backref=db.backref('user'))
    create_time: str = db.Column(db.DateTime, default=datetime.now)
    update_time:str = db.Column(db.DateTime, default=datetime.now,onupdate=datetime.now)
    articles = db.relationship('Article',backref="user")

    # def to_dict(self):
    #     return {c.name: getattr(self, c.name) for c in self.__table__.columns}
    def to_dict(self):
        '''将对象转换为字典数据'''
        user_dict = {
            "id": self.id,
            "username": self.username,
            "realname": self.realname,
            "avatar": self.avatar,
            "email": self.email,
            "remark": self.remark,
            "status": self.status,
            "dept_id": self.dept_id,
            "phone":self.phone,
            "role": self.role,
            #"articles":self.articles,
            "create_time": self.create_time,
            "update_time": self.update_time,
        }
        return user_dict
    @classmethod
    def to_model(cls, **kwargs):
        model = User()  # 实例化一个device对象
        columns = [c.name for c in cls.__table__.columns]  # 获取Devices模型定义的所有列属性的名字
        for k, v in kwargs.items():  # 遍历传入kwargs的键值
            if k in columns:  # 如果键包含在列名中，则为该device对象赋加对应的属性值
                setattr(model, k, v)
        return model
